package com.macken.wow.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.macken.wow.dao.CharacterDao;
import com.macken.wow.dao.UserDao;
import com.macken.wow.entity.CharacterInfo;
import com.macken.wow.entity.UserInfo;
import com.macken.wow.util.ServletUtil;
import com.macken.wow.util.SignatureUtil;

@Controller
public class UserCenterController {

	private CharacterDao charDao = CharacterDao.instance;
	private UserDao userDao = UserDao.instance;
	@RequestMapping("/u/index.do")
	public String index(HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserInfo user = ServletUtil.getSession(request, "user");
		if (user == null) {
			response.sendRedirect("/msg.jsp?msg=login");
			return "";
		}
		return "/usercenter/index.jsp";

	}

	@RequestMapping("/u/myrole.do")
	public String myrole(HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserInfo user = ServletUtil.getSession(request, "user");
		if (user == null) {
			response.sendRedirect("/msg.jsp?msg=login");
			return "";
		}

		int account = user.getWowId();
		List<CharacterInfo> chars = charDao.getRoles(account);
		request.setAttribute("chars", chars);
		return "/usercenter/myrole.jsp";
	}

	@RequestMapping("/u/change.do")
	public String changeIndex(HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserInfo user = ServletUtil.getSession(request, "user");
		if (user == null) {
			response.sendRedirect("/msg.jsp?msg=login");
			return "";
		}
		return "/usercenter/changepwd.jsp";
	}

	@RequestMapping("/u/changepwd.do")
	public void changepwd(HttpServletRequest request, HttpServletResponse response, @RequestParam String oldpwd,
			@RequestParam String newpwd) throws Exception {
		Gson gson = new Gson();
		UserInfo user = ServletUtil.getSession(request, "user");
		if (user == null) {
			response.getWriter().write(gson.toJson("fail"));
			return;
		}

		String cryOld = SignatureUtil.md5(oldpwd);
		if (cryOld.equals(user.userPwd)) {
			String cryNew = SignatureUtil.md5(newpwd);
			user.userPwd = cryNew;
			userDao.updateUserPwd(user);
			String userPass = SignatureUtil.sha1(user.userName + ":" + newpwd.toUpperCase()).toUpperCase();
			userDao.updateReamlPwd(user, userPass);
			response.getWriter().write(gson.toJson("success"));
			return;
		} else {
			response.getWriter().write(gson.toJson("fail"));
			return;
		}


	}
}
